//
//  OverInfomationViewController.m
//  PYWGetColor
//
//  Created by 杜文杰 on 2018/6/8.
//  Copyright © 2018年 dwj. All rights reserved.
//

#import "OverInfomationViewController.h"
#import "OverInfomationTableViewCell.h"
#import "OverInfomationHeadImgTableViewCell.h"
#import "OverInfomationQiyexinxiTableViewCell.h"
#import "OnePeopleCertificaViewController.h"
#import "QYCertificationViewController.h"
#import "WJSelectedPickerView.h"

@interface OverInfomationViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *mainTableView; // 主框架
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIButton *makesureBtn;
@property (nonatomic, strong) NSMutableArray *muDataArray;
@property (nonatomic, strong) UIImage *headImage; // 上传的头像
@property (nonatomic, strong) OverInfomationTableViewCell *sexCell; // 性别那个cell
@property (nonatomic, strong) NSDictionary *dataDic;
@end

@implementation OverInfomationViewController
// 获取信息
- (void)getInfoMations {
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=userinfo" parameters:@{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"error_code"]];
        if ([str isEqualToString:@"0"]) {
            self.dataDic = responseObject[@"data"];
            NSDictionary *dataDic = responseObject[@"data"];
            self.muDataArray[0][1][@"inputValue"] = dataDic[@"nickname"]; // 昵称
            if ([dataDic[@"usersex"] isEqualToString:@"1"]) { // 性别
                self.muDataArray[0][2][@"inputValue"] = @"男";
            }else if([dataDic[@"usersex"] isEqualToString:@"2"]){
                self.muDataArray[0][2][@"inputValue"] = @"女";
            }else{
                self.muDataArray[0][2][@"inputValue"] = @"保密";
            }
            self.muDataArray[0][3][@"inputValue"] = dataDic[@"userphone"];// 电话
            self.muDataArray[1][0][@"inputValue"] = dataDic[@"useraddress"];// 地址
            self.muDataArray[3][0][@"inputValue"] = dataDic[@"companyname"];// 公司全称
            self.muDataArray[3][1][@"inputValue"] = dataDic[@"companyphone"];// 公司电话
            self.muDataArray[4][0][@"inputValue"] = dataDic[@"companyaddress"];// 公司地址
            [UserModel sharedInstanced].headImg = dataDic[@"avatar"]; // 头像
            [UserModel sharedInstanced].nameNick = dataDic[@"nickname"]; // 昵称
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:dataDic[@"avatar"]]]];
            self.headImage = image;
            [self.mainTableView reloadData];
        }else{
            ShowMessage(@"操作失败");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
// 修改保存
- (void)saveMineInfoMation{
    [self showprogressHUD];
    NSString *nameStr = self.muDataArray[0][1][@"inputValue"]; // 昵称
    NSString *sexStr = self.muDataArray[0][2][@"inputValue"]; // 性别
    if ([sexStr isEqualToString:@"男"]) {
        sexStr = @"1";
    }else if([sexStr isEqualToString:@"女"]){
        sexStr = @"2";
    }else{
        sexStr = @"0";
    }
    NSString *telStr = self.muDataArray[0][3][@"inputValue"]; // 电话
    NSString *addressStr = self.muDataArray[1][0][@"inputValue"]; // 地址
    NSString *companyNameStr = self.muDataArray[3][0][@"inputValue"]; // 公司全称
    NSString *companyTelStr = self.muDataArray[3][1][@"inputValue"]; // 公司电话
    NSString *companyAddrStr = self.muDataArray[4][0][@"inputValue"]; // 公司地址
    
    NSDictionary *parameter = @{@"user_id":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token,@"nickname":nameStr,@"sex":sexStr,@"mobile":telStr,@"address":addressStr,@"companyname":companyNameStr,@"companytell":companyTelStr,@"companyaddr":companyAddrStr};
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=saveinfo" parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (!self.headImage) {
            self.headImage = [UIImage imageNamed:@"list_headerImg"];
        }
            NSData *data = UIImageJPEGRepresentation(self.headImage, .1);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
            [formData appendPartWithFileData:data name:@"avatar" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"error_code"] isEqualToString:@"0"]) {
            [self getInfoMations];
            [self.view makeToast:@"修改成功" duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
//                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else{
        }
        
        [self hiddenProgressHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
    }];
    
}

- (void)buttonAction
{
    NSLog(@"确认按钮");
    [self saveMineInfoMation];
}
- (void) btnAction:(UIButton *)btn
{
    WJSelectedPickerView *view = [[WJSelectedPickerView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) selectedHandle:^(NSString *str) {
        NSLog(@"%@",[NSString stringWithFormat:@"年份   %@",str]);
        self.muDataArray[0][2][@"inputValue"] = str;
        self.sexCell.textField.text = str;
    }];
    [view show];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = NO;
    self.title = @"完善信息";
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 25)];
    UIButton *button = [[UIButton alloc] initWithFrame:contentView.bounds];
    [button.titleLabel sizeToFit];
    self.makesureBtn = button;
    [button setTitle:@"确定" forState:UIControlStateNormal];
    [button setTitleColor:getColor(mainColor) forState:UIControlStateNormal];
    button.titleLabel.font = DEF_FontSize_14;
    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:button];
    UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithCustomView:contentView];
    self.navigationItem.rightBarButtonItems = @[button2];
    
    [self.view addSubview:self.mainTableView];
    [self getInfoMations];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
}
#pragma mark -UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.muDataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *dataArray = self.muDataArray[section];
    return dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        OverInfomationHeadImgTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([OverInfomationHeadImgTableViewCell class])];
        cell.dataDic = self.muDataArray[indexPath.section][indexPath.row];
        cell.headImageView.image = self.headImage;
        __weak typeof(cell)weakselfcell = cell;
        __weak typeof(self)weakself = self;
        cell.imgTapBlock = ^{
            [weakself selectPhotoAlbumWithSelectPhotoHandle:^(UIImage *img) {
                NSLog(@"上传头像");
                weakselfcell.headImageView.image = img;
                weakself.headImage = img;
            }];
        };
        return cell;
    }
    if (indexPath.section == 0 && indexPath.row == 2) {
        OverInfomationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([OverInfomationTableViewCell class])];
        cell.dataDic = self.muDataArray[indexPath.section][indexPath.row];
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50 / HEIGHT_6S_SCALE)];
        btn.backgroundColor = [UIColor clearColor];
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:btn];
        self.sexCell = cell;
        return cell;
    }
    if (indexPath.section == 2) {
        OverInfomationQiyexinxiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([OverInfomationQiyexinxiTableViewCell class])];
        return cell;
    }
    OverInfomationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([OverInfomationTableViewCell class])];
    cell.dataDic = self.muDataArray[indexPath.section][indexPath.row];
    cell.getTextFieldClick = ^(NSString *str) {
        NSLog(@"第几个组%ld",indexPath.section);
        self.muDataArray[indexPath.section][indexPath.row][@"inputValue"] = str;
        
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 70 / HEIGHT_6S_SCALE;
    }
    return 50 / HEIGHT_6S_SCALE;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 3) {
        return 31 / HEIGHT_6S_SCALE;
    }
    return 16 / HEIGHT_6S_SCALE;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 3) {
        UIView *bgView = [[UIView alloc]init];
        bgView.backgroundColor = getColor(dividerColor);
        
        UILabel *tsLabel = [[UILabel alloc]initWithFrame:CGRectMake(20 / WIDTH_6S_SCALE, 0, SCREEN_WIDTH, 31 / HEIGHT_6S_SCALE)];
        tsLabel.backgroundColor = [UIColor clearColor];
        tsLabel.textColor = getColor(textColor);
        tsLabel.textAlignment = NSTextAlignmentLeft;
        tsLabel.font = DEF_FontSize_12;
        tsLabel.text = @"为了尽快通过审核,请确认一下信息准确无误";
        [bgView addSubview:tsLabel];
        return bgView;
    }
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = getColor(dividerColor);
    
    return bgView;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = getColor(blueColor);
    
    return bgView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            NSLog(@"地址");
        }
        if (indexPath.row == 1) {
            NSLog(@"证件上传");
            OnePeopleCertificaViewController *VC = [[OnePeopleCertificaViewController alloc]init];
            VC.dataDic = self.dataDic;
            [self.navigationController pushViewController:VC animated:YES];
        }
    }
    if (indexPath.section == 4) {
        if (indexPath.row == 0) {
            NSLog(@"公司地址");
        }
        if (indexPath.row == 1) {
            NSLog(@"公司证件上传");
            QYCertificationViewController *VC = [[QYCertificationViewController alloc]init];
            VC.dataDic = self.dataDic;
            [self.navigationController pushViewController:VC animated:YES];
        }
    }
}
#pragma mark - init
- (UITableView *)mainTableView
{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - SafeAreaBottomHeight - SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _mainTableView.backgroundColor = getColor(whiteColor);
        _mainTableView.tableHeaderView = self.headerView;
        _mainTableView.tableFooterView = self.footerView;
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.showsVerticalScrollIndicator = NO;
        _mainTableView.showsHorizontalScrollIndicator = NO;
        _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        // 动态行高
        _mainTableView.rowHeight = UITableViewAutomaticDimension;
        // 预估行高
        _mainTableView.estimatedRowHeight = 80;
        [_mainTableView registerClass:[OverInfomationTableViewCell class] forCellReuseIdentifier:NSStringFromClass([OverInfomationTableViewCell class])];
        [_mainTableView registerClass:[OverInfomationHeadImgTableViewCell class] forCellReuseIdentifier:NSStringFromClass([OverInfomationHeadImgTableViewCell class])];
        [_mainTableView registerClass:[OverInfomationQiyexinxiTableViewCell class] forCellReuseIdentifier:NSStringFromClass([OverInfomationQiyexinxiTableViewCell class])];
        
    }
    return _mainTableView;
}
- (UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
        _headerView.backgroundColor = [UIColor grayColor];
    }
    return _headerView;
}
- (UIView *)footerView
{
    if (!_footerView) {
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
    }
    return _footerView;
}
- (NSMutableArray *)muDataArray
{
    if (!_muDataArray) {
        _muDataArray = @[@[@{@"titleName":@"头像",@"inputValue":@""}.mutableCopy,
                           @{@"titleName":@"昵称",@"inputValue":@""}.mutableCopy,
                           @{@"titleName":@"性别",@"inputValue":@""}.mutableCopy,
                           @{@"titleName":@"电话",@"inputValue":@""}.mutableCopy].mutableCopy,
                         @[@{@"titleName":@"地址",@"inputValue":@""}.mutableCopy,
                           @{@"titleName":@"证件上传",@"inputValue":@""}.mutableCopy].mutableCopy,
                         @[@{@"titleName":@"企业信息管理",@"inputValue":@""}.mutableCopy].mutableCopy,
                         @[@{@"titleName":@"公司全称",@"inputValue":@""}.mutableCopy,
                           @{@"titleName":@"公司电话",@"inputValue":@""}.mutableCopy].mutableCopy,
                         @[@{@"titleName":@"公司地址",@"inputValue":@""}.mutableCopy,
                           @{@"titleName":@"证件上传",@"inputValue":@""}.mutableCopy].mutableCopy,
                         ].mutableCopy;
    }
    return _muDataArray;
}
- (NSDictionary *)dataDic
{
    if (!_dataDic) {
        _dataDic = @{}.mutableCopy;
        
    }
    return _dataDic;
}
@end
